package com.campus.web.control;

import com.campus.model.Permission;
import com.campus.model.Role;
import com.campus.service.PermService;
import com.campus.web.vo.ResponseResult;
import com.campus.web.vo.TokenManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import com.campus.service.UserService;
import com.campus.model.User;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.constraints.NotBlank;
import java.util.List;

import static com.campus.common.BusinessConstants.TOKEN_KEY;
import static com.campus.common.BusinessConstants.USER_KEY;

@Controller
@RequestMapping("/users")
@Slf4j
@Validated
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private PermService permService;

    // 登录：POST /users/login
    @PostMapping("/login")
    @ResponseBody
    public ResponseResult<String> login(HttpServletRequest request,
                                        @NotBlank @RequestParam String username,
                                        @NotBlank @RequestParam String password) {

        log.info(" username: {}, password: {}", username, password);
        User user = userService.login(username, password);
        if (ObjectUtils.isEmpty(user)) {
            return ResponseResult.error(HttpStatus.OK, "用户名或密码错误");
        }
        // session 中存储user
        HttpSession session = request.getSession();
        session.setAttribute(USER_KEY, user.getLoginName());
        String token = TokenManager.getToken(user);
        session.setAttribute(TOKEN_KEY, token);
        //获取用户角色
        List<String> stringList = TokenManager.getRolesFromToken(token);
        log.info("roles: {}", stringList);
        return ResponseResult.ok(token, "登录成功");
    }

    // 创建用户：POST /users
    @PostMapping()
    @ResponseBody
    public ResponseResult<String> addUser(@RequestBody @Validated User user) {
        log.info(" username: {}, password: {}", user.getLoginName(), user.getPassword());
        userService.addUser(user);  // 你可以根据实际的业务逻辑调用相应的方法
        return ResponseResult.ok("添加成功");
    }

    // 查询用户通过ID：
    @GetMapping("/id/search")
    @ResponseBody
    public ResponseResult<User> queryUserById(@RequestParam @NotBlank int id) {
        log.info(" User: {}", userService.queryUserById(id));
        User user = userService.queryUserById(id);
        return ResponseResult.ok(user, "查询成功");
    }

    // 查询用户通过用户名：GET /users/search
    @GetMapping("/name/search")
    @ResponseBody
    public ResponseResult<User> queryUserByName(@RequestParam @NotBlank String name) {
        log.info(" User: {}", userService.queryUserByName(name));
        User user = userService.queryUserByName(name);
        return ResponseResult.ok(user, "查询成功");
    }

    // 分配角色给用户：POST /roles
    @PostMapping("/roles/users")
    @ResponseBody
    public ResponseResult<String> addUserRole(@RequestParam @NotBlank int userId,
                                              @RequestParam @NotBlank int roleId) {
        log.info(" userId: {}, roleId: {}", userId, roleId);
        userService.addUserRole(userId, roleId);
        return ResponseResult.ok("添加成功");
    }

    // 创建角色：POST /roles
    @PostMapping("/roles")
    @ResponseBody
    public ResponseResult<String> addRole(@RequestBody @Validated Role role) {
        log.info(" role: {}", userService.addRole(role));
        return ResponseResult.ok("添加成功");
    }

    // 创建权限：POST /permissions
    @PostMapping("/permissions")
    @ResponseBody
    public ResponseResult<String> addPermission(@RequestBody @Validated Permission permission) {
        log.info(" permission: {}", userService.addPermission(permission));
        return ResponseResult.ok("添加成功");
    }

    // 创建小组：POST /groups
    @PostMapping("/groups")
    @ResponseBody
    public ResponseResult<String> addGroup(@RequestParam String groupName,
                                           @RequestParam int classId) {
        log.info(" groupName: {}, classId: {}", groupName, classId);
        userService.addGroup(groupName, classId);
        return ResponseResult.ok("添加成功");
    }
    // 根据角色名字查询用户权限GET
    @GetMapping("/permissions")
    @ResponseBody
    public ResponseResult<List<String>> queryPermissionByRoleName(@RequestParam List<String> roleName) {
        log.info(" roleName: {}", roleName);
        List<String> permissions = permService.findPermsByRoleName(roleName);
        return ResponseResult.ok(permissions, "查询成功");
    }

}
